package Core;
/*
 *  J2Egn version 2.6.28
 *  Author: Van Tan Tai 2010-2011
 *  just for Touch devices
 */
import java.util.Vector;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class Touch {
	
	public final static int NOTHING = -1;

	public static int IDcurr = NOTHING;
	public static int IDprev = NOTHING;
	public static int IDdown = NOTHING;
	public static boolean isPressed = false;
	public static int holdTime = 0;
	public static int x,y; // current pointer on device
	public static int xDown, xUp, yDown, yUp;
	
	private static Vector vec = new Vector();
	
	private static class Area{
		int ID;
		int x, y , w, h;
		public Area(int ID, int x, int y , int w, int h) {
			this.ID = ID; this.x = x; this.y = y; this.w = w; this.h = h;
		}
	}
	
	public static void destroy(){
		vec = null;
	}
	
	public static void resetPos(){
		holdTime = x = y = xDown = xUp = yDown = yUp = 0;
	}
	
	public static void addTouchArea(int ID, int x, int y, int w, int h){
		vec.addElement(new Area(ID, x, y, w, h));
	}
	
	public static int click(int x, int y){
		for(int i = 0; i < vec.size(); i++){
			Area o = (Area)vec.elementAt(i);
			if( x >= o.x && x <= o.x + o.w && y >= o.y && y <= o.y + o.h ){
				return o.ID;
			}
		}
		return NOTHING;
	}
	
	public static void releaseTouchArea(){
		for(int i = 0; i < vec.size(); i++){
			Object o = vec.elementAt(i);
			if(o != null)
				o = null;
		}
		vec.removeAllElements();
		System.gc();
	}
	
	public static void removeTouchID(int ID){
		for(int i = 0; i < vec.size(); i++)
			if(((Area)vec.elementAt(i)).ID == ID){
				vec.removeElementAt(i);
				break;
			}
	}
	
	public static void drawImage(Graphics g, int ID, Image img){
		for(int i = 0; i < vec.size(); i++)
			if(((Area)vec.elementAt(i)).ID == ID){
				g.drawImage(img, ((Area)vec.elementAt(i)).x, ((Area)vec.elementAt(i)).y, 0);
				break;
			}
	}
	
	// debug
	public static void drawMe(Graphics g){
		for(int i = 0; i < vec.size(); i++){
			Area o = (Area)vec.elementAt(i);
			g.setColor(0x00FF00);
			g.drawRect(o.x, o.y, o.w, o.h);
			g.drawString(""+ o.ID, o.x + 5, o.y + 5, 0);
		}
	}
}
